﻿using Nature.Core.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Nature.Core.DDD.DomainEvent
{
    public abstract class BaseDomainEvent:IDomainEvent
    {
        public static T CreateEvent<T>() where T : BaseDomainEvent, new()
        {
            return new T();
        }

        protected static IDomainEventHandlerFac DomainEventHandlerFac
        {
            get 
            {
                return new DomainEventHandlerFac();
            }
        }

        protected static void Raise<T>(T domainEvent) where T:IDomainEvent
        {
            try
            {
                //获取所有的处理器
                var handlers = DomainEventHandlerFac.GetDomainEventHandlerFor<T>();
                foreach (var handler in handlers)
                {
                    var content = new DomainEventContext<T>(domainEvent);
                    handler.Handle(content);
                }
            }
            catch (BaseException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw new FrameExcetpion("领域事件调用错误。", e);
            }
        }

        public abstract void Raise();
    }
}
